import re
import argparse

def convert_hex_to_binary(input_file, output_file):
    # 读取输入文件
    with open(input_file, "r") as f:
        hex_text = f.read()

    # 提取所有十六进制字节（去掉空格和换行）
    hex_bytes = re.findall(r"[0-9a-fA-F]{2}", hex_text)

    # 打印前15个字节和末尾15个字节
    print("\nHex data preview:")
    print(f"First 15 bytes: {hex_bytes[:15]}")
    print(f"Last 15 bytes: {hex_bytes[-15:]}\n")

    # 转换成二进制数据
    binary_data = bytes.fromhex("".join(hex_bytes))

    # 写入输出二进制文件
    with open(output_file, "wb") as f:
        f.write(binary_data)

    print(f"Done! Saved as {output_file}")

if __name__ == "__main__":
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description="Convert hexadecimal ASCII file to binary.")
    parser.add_argument("input_file", help="The input file containing hex data (ASCII format)")
    parser.add_argument("output_file", help="The output file to save the binary data")

    # 解析命令行参数
    args = parser.parse_args()

    # 调用转换函数
    convert_hex_to_binary(args.input_file, args.output_file)
